package com.squid.cloud.common.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSourceFactory;

@Configuration
@MapperScan(basePackages = "com.squid.cloud.model.dao")
public class MyBatisConfig {

	@Value("${spring.datasource.driverClassName}")
	private String driverClass;
	@Value("${spring.datasource.url}")
	private String url;
	@Value("${spring.datasource.username}")
	private String username;
	@Value("${spring.datasource.password}")
	private String password;
	@Value("${mybatis.typeAliasesPackage}")
	private String typeAliasesPackage;
	@Value("${mybatis.mapperLocations}")
	private String mapperLocations;

	/**
	 * @Title: getDataSource @Description: 创建数据源 @param @return @return
	 *         DataSource @throws
	 */
	@Bean
	public DataSource getDataSource() {
		try {
			Properties props = new Properties();
			props.put("driverClass", driverClass);
			props.put("url", url);
			props.put("username", username);
			props.put("password", password);
			return DruidDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @Title: sqlSessionFactory 
	 * @Description:
	 *     根据数据源创建SqlSessionFactory 
	 * @param 
	 *         DataSource  
	 * @return  SqlSessionFactory
	 * @throws Exception 
	 */
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception {
		SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
		sfb.setDataSource(ds);
		// 下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
		sfb.setTypeAliasesPackage(typeAliasesPackage);
		sfb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
		return sfb.getObject();
	}
}
